/* 登录页思路分析
1.切换登录与注册盒子
2.登录功能
3.注册功能
*/

//1.点击切换登录与注册

document.querySelector('.login a').addEventListener('click', function () {
    document.querySelector('.login').style.display = 'none'
    document.querySelector('.register').style.display = 'block'
})
document.querySelector('.register a').addEventListener('click', function () {
    document.querySelector('.register').style.display = 'none'
    document.querySelector('.login').style.display = 'block'
})

//2.注册  
//2.1收集数据 2.2校验数据 2.3发送请求 2.4处理数据
document.querySelector('.register .btn').addEventListener('click', function (e) {
    e.preventDefault()
    let username = document.querySelector('.register [name="username"]').value
    let password = document.querySelector('.register [name="password"]').value
    console.log(username, password)
    //非空判断
     if (username === '' || password === '') {
        return Toast.fail('不能为空哟')
    } 
    //正则判断
    if (/^\w{6,15}/.test(username) === false || /^\w{6,15}/.test(password) === false) {
        return Toast.fail('账号或密码格式错误')
    }

    axios({
        url: '/api/register',
        method: 'post',
        data: { username, password },
    }).then(res => {
        //成功回调
        console.log(res)
        Toast.info(res.data.message)
        if(res.data.code===0){
            document.querySelector('.register a').click()
        }
    })


})
document.querySelector('.login .btn').addEventListener('click', function (e) {
    e.preventDefault()
    let username = document.querySelector('.login [name="username"]').value
    let password = document.querySelector('.login [name="password"]').value
    console.log(username, password)
    if (username === '' || password === '') {
        return Toast.fail('不能为空哟')
    }
    if (!/^\w{6,15}/.test(username) || !/^\w{6,15}/.test(password)) {
        return Toast.fail('账号或密码格式错误')
    }
    axios({
        url: '/api/login',
        method: 'post',
        data: { username, password },
    }).then(res => {
        //成功回调
        console.log(res)
        Toast.info(res.data.message)
        if(res.data.code===0){
            //硬盘存储token
            localStorage.setItem('token',res.data.token)
            //跳转首页
            location.href='./index.html'
        }
    })
   


})
